package com.chukun.spring.beans.defination;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author chukun
 *  将beanDefinition注册到ioc容器的方式
 */
@Import(AnnotationBeanDefinitionDemo.InnerConfiguration.class)
public class AnnotationBeanDefinitionDemo {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        //注册配置
        context.register(InnerConfiguration.class);

        // 指定beanName的方式注册bean
        registerBeanDefinition(context,"chukun-user",User.class);
        // 不指定beanName的方式注册bean
        registerBeanDefinition(context,User.class);

        // 刷新ioc容易
        context.refresh();

        Map<String, InnerConfiguration> beansMap = context.getBeansOfType(InnerConfiguration.class);

        // 按照类型依赖查找
        System.out.println("configurations类型所有的beans: " +beansMap);

        Map<String, User> usersMap = context.getBeansOfType(User.class);
        System.out.println("user类型所有的beans: " +usersMap);

        // 关闭ioc容器
        context.close();

    }


    /**
     * 命名bean的方式注册bean
     * @param registry
     * @param beanName
     * @param beanClass
     */
    public static void registerBeanDefinition(BeanDefinitionRegistry registry, String beanName, Class<?> beanClass) {

        BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);

        definitionBuilder.addPropertyValue("id", 20L)
                .addPropertyValue("name","guo");
        // 注册bean的两种方式
        if (StringUtils.hasText(beanName)) {
            // 指定beanName的方式注册beanDefinition
            registry.registerBeanDefinition(beanName,definitionBuilder.getBeanDefinition());
        } else {
            // 默认生成beanName的方式注册beanDefinition
            BeanDefinitionReaderUtils.registerWithGeneratedName(definitionBuilder.getBeanDefinition(),registry);
        }
    }

    /**
     * 重载注册bean的代码
     * @param registry
     * @param beanClass
     */
    public static void registerBeanDefinition(BeanDefinitionRegistry registry, Class<?> beanClass) {
        registerBeanDefinition(registry,"",beanClass);
    }


    @Component
    public static class InnerConfiguration{

        @Bean(name = {"user","chukun-user"})
        public User user() {
            User user = new User();
            user.setId(10L);
            user.setName("chukun");
            return user;
        }
    }
}
